import json, re
import os

from django.contrib.auth import login, authenticate, logout
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection
from fdfs_client.client import Fdfs_client

from users.models import User
from ihome.utils.mixins import LoginRequiredMixin


# 注册
class RegisterView(View):
    def post(self, request):
        # 接收参数
        json_data = json.loads(request.body.decode())
        mobile = json_data.get('mobile')
        sms_code = json_data.get('phonecode')
        password = json_data.get('password')

        # 校验参数
        if not all([mobile, sms_code, password]):
            return JsonResponse({
                "errno": "400",
                "errmsg": "缺省参数"
            })
        if not re.match(r'1[3-9]\d{9}', mobile):
            return JsonResponse({
                "errno": "400",
                "errmsg": "手机号格式错误"
            })
        # 校验手机号是否重复注册
        try:
            count = User.objects.filter(mobile=mobile).count()
        except User.DoesNotExist:
            return JsonResponse({
                "errno": "400",
                "errmsg": "数据库查询错误"
            })
        if count != 0:
            return JsonResponse({
                "errno": "400",
                "errmsg": "手机号重复"
            })
        # 未注册过,校验密码
        if not re.match(r'^[a-zA-Z0-9_-]{8,20}$', password):
            return JsonResponse({
                "errno": "400",
                "errmsg": '密码格式错误'
            })
        # 判断输入的短信验证码内容是否正确
        redis_conn = get_redis_connection('verify_code')
        sms_code_redis = redis_conn.get('sms_code_%s' % mobile)
        if not sms_code:
            return JsonResponse({
                "errno": "400",
                "errmsg": '验证码过期'
            })
        if sms_code != sms_code_redis:
            return JsonResponse({
                "errno": "400",
                "errmsg": '验证码错误'
            })
        user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        # 设置状态保持, session
        login(request, user=user)
        # 设置cookie
        response = JsonResponse({
            "errno": "0",
            "errmsg": "注册成功"
        })
        response.set_cookie('mobile', mobile, max_age=14 * 24 * 3600)
        # 响应结果
        return response


class LoginView(View):
    def post(self, request):
        # 接收参数
        json_data = json.loads(request.body.decode())
        mobile = json_data.get('mobile')
        password = json_data.get('password')
        # 校验参数
        if not all([mobile, password]):
            return JsonResponse({
                "errno": "400",
                "errmsg": "缺少参数"
            })
        if not re.match(r'1[3-9]\d{9}', mobile):
            return JsonResponse({
                "errno": 400,
                "errmsg": "手机号格式错误"
            })
        if not re.match(r'^[a-zA-Z0-9_-]{8,20}$', password):
            return JsonResponse({
                "errno": "400",
                "errmsg": '密码格式错误'
            })
        # 实现核心逻辑:认证用户登录,登录状态保持
        User.USERNAME_FIELD = 'mobile'
        user = authenticate(username=mobile, password=password)
        if not user:
            return JsonResponse({
                "errno": "400",
                "errmsg": '用户名或密码错误'
            })
        login(request, user)
        # 首页用户名展示
        response = JsonResponse({
            "errno": "0",
            "errmsg": "登录成功"
        })
        response.set_cookie('mobile', mobile, max_age=14 * 24 * 3600)
        # 响应结果
        return response

    # 判断是否登录
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({
                "errno": "400",
                "errmsg": "未登录"
            })
        data = {
            'name': request.user.username,
            'user_id': request.user.id,
        }
        return JsonResponse({
            "errno": "0",
            "errmsg": "已登录",
            "data": data
        })

    # 退出登录
    def delete(self, request):
        # 清理登录状态
        logout(request)
        # 清理用户名cookie
        response = JsonResponse({
            "errno": "0",
            "errmsg": "已注销"
        })
        response.delete_cookie('mobile')
        return response


class UserInfoView(LoginRequiredMixin,View):
    def get(self, request):
        user = request.user
        nginx_url = 'http://192.168.19.131:8888/'
        return JsonResponse({
            "data": {
                "avatar_url": nginx_url + user.avatar.name,
                "create_time": user.date_joined,
                "mobile": user.mobile,
                "name": user.username,
                "user_id": user.id
            },
            "errmsg": "OK",
            "errno": "0"
        })


class AvatarView(LoginRequiredMixin, View):
    def post(self, request):
        pic = request.FILES.get('avatar')
        pic = pic.read()
        client = Fdfs_client(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'utils/fastdfs/client.conf'))
        nginx_url = 'http://192.168.19.131:8888/'
        try:
            ret = client.upload_by_buffer(pic)['Remote file_id']
            User.objects.filter(id=request.user.id).update(avatar=ret)
        except Exception as e:
            return JsonResponse({
                "errno": 400,
                "errmsg": "图片上传失败"
            })
        return JsonResponse({
            "data": {
                "avatar_url": nginx_url + ret
            },
            "errno": "0",
            "errmsg": "头像上传成功"
        })


class NameView(LoginRequiredMixin, View):
    def put(self, request):
        req_data = json.loads(request.body)
        name = req_data.get('name')
        if not all([name]):
            return JsonResponse({
                "errno": "400",
                "errmsg": "缺少参数"
            })
        user = request.user
        try:
            user.username = name
            user.save()
        except:
            return JsonResponse({
                "errno": "0",
                "errmsg": "修改失败"
            })
        return JsonResponse({
            "errno": "0",
            "errmsg": "修改成功"
        })


class AuthNameView(LoginRequiredMixin, View):
    def post(self, request):
        req_data = json.loads(request.body)
        real_name = req_data.get('real_name')
        id_card = req_data.get('id_card')
        if not re.match(r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$', id_card):
            return JsonResponse({"errno": 400,
                                 "errmsg": "身份验证失败"})
        if not all([real_name, id_card]):
            return JsonResponse({
                "errno": "400",
                "errmsg": "缺少参数"
            })
        user = request.user
        try:
            user.real_name = real_name
            user.id_card = id_card
            user.save()
        except:
            return JsonResponse({
                "errno": "0",
                "errmsg": "添加失败"
            })
        return JsonResponse({
            "errno": "0",
            "errmsg": "认证信息保存成功"
        })

    def get(self, request):
        user = request.user
        id_card = user.id_card
        real_name = user.real_name
        return JsonResponse({
            "errno": "0",
            "data": {
                'id_card': id_card,
                'real_name': real_name
            },
            "errmsg": "OK"
        })